package com.tlcx.kfip.adapter.base;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;


/**
 * XRecyclerView的base适配器
 * Created by victor on 2016/10/27 10:26.
 * Email:zhuzhaoyang@yuanchuangyun.com
 */

public abstract class XRecyclerBaseAdapter<T> extends RecyclerView.Adapter<XRecyclerBaseAdapter.BaseViewHolder>{

    private List<T> mData;
    private Context mContext;
    private LayoutInflater mInflater;

    public XRecyclerBaseAdapter(Context context){
        this(context,null);
    }
    public XRecyclerBaseAdapter(Context context,List<T> data){
        mData = data == null ? new ArrayList<T>() :new ArrayList<>(data);
        mContext = context;
        mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    /**
     * 创建新view
     */
    @Override
    public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mInflater.inflate(getItemResource(viewType),parent,false);
        return new BaseViewHolder(view);
    }

    /**
     * 将数据与页面控件进行绑定
     */
    @Override
    public void onBindViewHolder(BaseViewHolder holder, int position) {
        bindData(holder,position,mData.get(position));
    }

    /**
     * 获得数据源总数
     */
    @Override
    public int getItemCount() {
        return mData == null ? 0 : mData.size();
    }

    /**
     * 需要子类实现，返回item的布局id
     */
    public abstract int getItemResource(int viewType);

    /**
     * 需要子类实现，替换onBindViewHolder方法
     */
    public abstract void bindData(BaseViewHolder holder,int position,T item);

    /**
     * 添加数据
     */
    public void addAllData(List<T> list){
        if (list != null && list.size() >0){
            mData.addAll(list);
        }
    }

    /**
     * 添加数据并刷新
     */
    public void addAllAndNotify(List<T> list){
        addAllData(list);
        notifyDataSetChanged();
    }

    /**
     * 自定义ViewHolder，继承自RecyclerView的ViewHolder
     */
    public static class BaseViewHolder extends RecyclerView.ViewHolder{
        private SparseArray<View> views = new SparseArray<>();
        private View convertView;

        public BaseViewHolder(View convertView){
            super(convertView);
            this.convertView = convertView;
        }
        public <T extends View> T getView(int resId){
            View view = views.get(resId);
            if (view == null) {
                view = convertView.findViewById(resId);
                views.put(resId,view);
            }
            return (T) view;
        }
    }

}
